using System;

namespace Common.Core.Objects
{
	public class ObjectCreator<SourceType,ObjectType> : IObjectCreator where ObjectType : class
	{
		public event EventHandler<ObjectCreatingEventArgs<SourceType,ObjectType>> Creating = delegate { };
		public event EventHandler<ObjectCreatedEventArgs<ObjectType>> Created = delegate { };

		protected virtual ObjectType CreateItem( SourceType source )
		{
			try
			{
				return Activator.CreateInstance<ObjectType>();
			}
			catch ( Exception )
			{
				return null;
			}
		}

		public ObjectType Create( SourceType source )
		{
			var args = new ObjectCreatingEventArgs<SourceType,ObjectType>( source );
			Creating( this, args );
			var result = args.Result ?? CreateItem( source );
			DefaultPropertyValueHelper.ApplyDefaultValues( result );
			Created( this, new ObjectCreatedEventArgs<ObjectType>( result ) );
			return result;
		}

		object IObjectCreator.Create( object source )
		{
			var result = Create( (SourceType)source );
			return result;
		}
	}
}